package com.xdan.memory.service;


import com.xdan.memory.config.RobotConfig;
import com.xdan.memory.entity.AlarmUser;
import com.xdan.memory.entity.Events;
import com.xdan.memory.listener.ListenerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class MatchUserService {


    @Resource
    private ImService im;

    @Resource
    private RobotConfig robotConf;

    public void matchAndSendMessage(String event, String appName, String message, String stack) throws Exception {
//        String chatId = robotConf.getChatId();
//        String errorInfo = RedisUtil.getStr(appName + ":" + event);
//        String errorInfo = RedisUtil.getStr(robotConf.getChatId());
//        if (!StringUtils.isEmpty(errorInfo) && "true".equals(errorInfo)) {
//            return;
//        }
        List<AlarmUser> alarmUsers = matchUser(event);
        StringBuilder alarmUser = new StringBuilder();
        alarmUsers.forEach(u -> {
            alarmUser.append("<at user_id=\\\"").append(u.getUserId()).append("\\\">").append(u.getName()).append("  ").append("</at>");
        });
        StringBuilder alarmUserJson = new StringBuilder();
        alarmUserJson.append("{\"text\":\"").append(alarmUser).append("\"}");


        log.info("【发送消息卡片】");
        im.SendAlertMessage(robotConf.getChatId(), event, appName, robotConf.getProduct(), ListenerService.processingErrorMessage(message), alarmUser.toString());
        log.info("【@匹配对象】{}",alarmUserJson.toString());
        im.SendMessage(robotConf.getChatId(), "text", alarmUserJson.toString());
//        RedisUtil.setEx(appName + ":" + event, message + stack, robotConf.getNotificationInterval(), TimeUnit.MINUTES);
    }


    private List<AlarmUser> matchUser(String event) {
        String newEvent = extractTargetString(event);
        List<AlarmUser> alarmUser = new ArrayList<>();
        List<Events> events = robotConf.getEvents();

        String group = events.stream().filter(e -> e.getEventName().equals(newEvent)).findFirst().map(Events::getGroup).orElse("default");

        robotConf.getAlarmUser().forEach(u -> {
            if (u.getGroup().equals(group)) {
                alarmUser.add(u);
            }
        });

        return alarmUser;
    }

    public static String extractTargetString(String input) {
        Pattern pattern = Pattern.compile("([a-zA-Z0-9.$_]+)\\(.*?\\)");
        Matcher matcher = pattern.matcher(input);

        // 如果找到匹配项，则返回匹配到的部分，否则返回原始字符串
        if (matcher.find()) {
            return matcher.group();
        } else {
            return input;
        }
    }
}